package com.ruoyi.system.outto.goods.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.model.domain.ArtRec;
import com.ruoyi.system.model.domain.GameAttribute;
import com.ruoyi.system.model.domain.GoodsInfoImg;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.model.mapper.AccountInfoMapper;
import com.ruoyi.system.model.mapper.InfoImgMapper;
import com.ruoyi.system.outto.core.LCConstant;
import com.ruoyi.system.outto.core.OutUrlConstant;
import com.ruoyi.system.outto.dto.HttpUtil;
import com.ruoyi.system.outto.game.CommonApi;
import com.ruoyi.system.outto.goods.MOFANGAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @author lz
 * @version 1.0
 * @date 2022/8/16 22:58
 */
@Slf4j
@Service
public class MOFANGApiImpl implements MOFANGAPI {

    @Resource
    private CommonApi commonApi;
    @Value("${desc.title}")
    private String descTitle;

    @Resource
    private InfoImgMapper infoImgMapper;

    @Resource
    private AccountInfoMapper accountInfoMapper;
    @Resource
    private GoodsInfoMapper goodsInfoMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,SalePartner salePartner) {
        Map<String, Object> resultMap = new HashMap<>();

        Map<String, Object> params = params(goodsInfoAndAttrValueDto,"add",salePartner);
        log.info("魔方添加接口请求参数={}", JSONObject.toJSONString(params));
        Map<String, Object> header = new HashMap<>();
        header.put("token",salePartner.getSaleKey());
        String result = HttpUtils.sendPost(salePartner.getTwoOther()+"/api_publish", JSONObject.toJSONString(params), "application/json");
        log.info("魔方添加接口返回参数={}", result);
        JSONObject resultJson = JSONObject.parseObject(result);
        String data = resultJson.getString("data");
        if (!"0".equals(resultJson.getString("code"))){
            resultMap.put("code",500);
        }else {
            resultMap.put("code",200);
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(salePartner.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            if(CollectionUtils.isNotEmpty(artRecs)) {
                artRecs.get(0).setOutid(data);
                artRecMapper.updateArtRec(artRecs.get(0));
            }else{
                artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
                artRecreq.setCreateId(goodsInfoAndAttrValueDto.getCreateId());
                artRecreq.setType(LCConstant.interAdd);
                artRecreq.setConfig(salePartner.getId());
                artRecreq.setSaleCode(salePartner.getSaleName());
                artRecreq.setOutid(data);
                artRecMapper.insertArtRec(artRecreq);
            }
        }
        //上架
        upperdelGame(goodsInfoAndAttrValueDto,salePartner);
        resultMap.put("req",JSONObject.toJSONString(params));
        resultMap.put("res",result);
        resultMap.put("msg",resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto , SalePartner salePartner) {
        Map<String, Object> resultMap = new HashMap<>();

        Map<String, Object> params = params(goodsInfoAndAttrValueDto,"update",salePartner);
        log.info("魔方编辑接口请求参数={}", JSONObject.toJSONString(params));
        Map<String, Object> header = new HashMap<>();
        header.put("token",salePartner.getSaleKey());
        String result = HttpUtils.sendPost(salePartner.getTwoOther()+"/api_publish", JSONObject.toJSONString(params), "application/json");
        log.info("魔方编辑接口返回参数={}", result);

        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"0".equals(resultJson.getString("code"))){
            resultMap.put("code",500);
        }else {
            resultMap.put("code",200);
        }
        resultMap.put("req",JSONObject.toJSONString(params));
        resultMap.put("res",result);
        resultMap.put("msg",resultJson);

        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult upperdelGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,SalePartner salePartner) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("ys_key", salePartner.getSaleKey());
        long timestamp = System.currentTimeMillis()/1000;
        params.put("ys_timestamp", timestamp);
        String cover = "key="+salePartner.getSaleKey()+",secret="+salePartner.getOther()+",timestamp="+timestamp;
        String cover2 = DigestUtils.md5Hex(cover);
        String sign = DigestUtils.sha1Hex(cover2+timestamp);
        params.put("ys_sign", sign);
        params.put("ys_up_id", descTitle+goodsInfoAndAttrValueDto.getId());
        log.info("魔方上架接口请求参数={}", JSONObject.toJSONString(params));
        String result = HttpUtils.sendPost(salePartner.getTwoOther()+"/api_upper", JSONObject.toJSONString(params), "application/json");
        log.info("魔方上架接口返回参数={}", result);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"0".equals(resultJson.getString("code"))){
            resultMap.put("code",500);
        }else {
            resultMap.put("code",200);
        }
        resultMap.put("req",JSONObject.toJSONString(params));
        resultMap.put("res",result);
        resultMap.put("msg",resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,SalePartner salePartner) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("ys_key", salePartner.getSaleKey());
        long timestamp = System.currentTimeMillis()/1000;
        params.put("ys_timestamp", timestamp);
        String cover = "key="+salePartner.getSaleKey()+",secret="+salePartner.getOther()+",timestamp="+timestamp;
        String cover2 = DigestUtils.md5Hex(cover);
        String sign = DigestUtils.sha1Hex(cover2+timestamp);
        params.put("ys_sign", sign);
        params.put("ys_up_id", descTitle+goodsInfoAndAttrValueDto.getId());
        log.info("魔方删除接口请求参数={}", JSONObject.toJSONString(params));
        String result = HttpUtils.sendPost(salePartner.getTwoOther()+"/api_under", JSONObject.toJSONString(params), "application/json");
        log.info("魔方删除接口返回参数={}", result);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"0".equals(resultJson.getString("code"))){
            resultMap.put("code",500);
        }else {
            resultMap.put("code",200);
            ArtRec artRecreq = new ArtRec();
            artRecreq.setConfig(salePartner.getId());
            artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
            List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
            if(CollectionUtils.isNotEmpty(artRecs)) {
                artRecMapper.deleteArtRecById(artRecs.get(0).getId());
            }
        }
        resultMap.put("req",JSONObject.toJSONString(params));
        resultMap.put("res",result);
        resultMap.put("msg",resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    private Map<String, Object> params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto,String type,SalePartner sa) {
        Map<String, Object> params = new TreeMap<>();
        params.put("ys_key", sa.getSaleKey());
        long timestamp = System.currentTimeMillis()/1000;
        params.put("ys_timestamp", timestamp);
        String cover = "key="+sa.getSaleKey()+",secret="+sa.getOther()+",timestamp="+timestamp;
        String cover2 = DigestUtils.md5Hex(cover);
        String sign = DigestUtils.sha1Hex(cover2+timestamp);
        params.put("ys_sign", sign);
        params.put("ys_up_id", descTitle+goodsInfoAndAttrValueDto.getId());
        params.put("ys_type", type);
        params.put("ys_no", descTitle+goodsInfoAndAttrValueDto.getId());
        if(goodsInfoAndAttrValueDto.getCarrierName().equals("游戏官方")) {
            params.put("ys_qufu1", "官服");
        }else{
            params.put("ys_qufu1", "B服");
        }
        params.put("ys_title", descTitle+goodsInfoAndAttrValueDto.getId()+goodsInfoAndAttrValueDto.getDes().replace("+",""));
        BigDecimal bigDecimal = commonApi.addPrice(goodsInfoAndAttrValueDto.getPrice(), sa.getSeleep());
        commonApi.setPrice(bigDecimal,goodsInfoAndAttrValueDto.getId(),sa);
        params.put("ys_price", bigDecimal);
        params.put("ys_level", StringUtils.isEmpty(goodsInfoAndAttrValueDto.getF7())?"0":goodsInfoAndAttrValueDto.getF7());
        if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF2())) {
            GameAttribute gameAttribute1 = gameAttributeMapper.selectGameAttributeById(Long.valueOf(goodsInfoAndAttrValueDto.getF2()));
            if(gameAttribute1.getFieldName().equals("未绑定邮箱")) {
                params.put("ys_emailrealname", "未绑定邮箱");
            }else if(gameAttribute1.getFieldName().equals("送已实名邮箱")) {
                params.put("ys_emailrealname", "送实名邮箱");
            }else if(gameAttribute1.getFieldName().equals("送未实名邮箱")) {
                params.put("ys_emailrealname", "送未实名邮箱");
            }else{
                params.put("ys_emailrealname", "未绑定邮箱");
            }
        }
        if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF11())) {
            params.put("ys_wxjssj", goodsInfoAndAttrValueDto.getF11().split(",").length);
            List<GameAttribute> gameAttributeList = getGameAttributs(goodsInfoAndAttrValueDto.getF11());
            String wxjs = "";
            for(GameAttribute gameAttribute1 : gameAttributeList){
                wxjs+=","+gameAttribute1.getFieldName();
            }
            params.put("ys_wuxingjuese", "五星角色"+(wxjs.substring(1)));
        }
        if(StringUtils.isNotEmpty(goodsInfoAndAttrValueDto.getF17())) {
            params.put("ys_wxwqsj", goodsInfoAndAttrValueDto.getF17().split(",").length);
            List<GameAttribute> gameAttributeList = getGameAttributs(goodsInfoAndAttrValueDto.getF17());
            String wxwq = "";
            for(GameAttribute gameAttribute1 : gameAttributeList){
                wxwq+=","+gameAttribute1.getFieldName();
            }
            if(StringUtils.isNotEmpty(wxwq)) {
                params.put("ys_wuxingjuese", "五星武器" + (wxwq.substring(1)));
            }
        }
        GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
        goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
        goodsInfoImg.setType(Constants.STR_1);
        List<GoodsInfoImg> infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);
        String imgs = "";
        if (!CollectionUtils.isEmpty(infoImgs)) {
            imgs = infoImgs.stream().map(i -> i.getImgUrl()).collect(Collectors.joining(","));
        } else {
            imgs =  LCConstant.defaultImg;
        }
        params.put("ys_imgs", imgs);
        return params;
    }

    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }

    private List<GameAttribute> getGameAttributs(String ids) {
        return gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                Long.class));
    }

    public static void main(String[] args) {
        Map<String, String> params = new HashMap<>();
        params.put("gameId", "12");
        String result = HttpUtil.doGet("http://api.axyds.com/game/property", params, null);
        System.out.println(result);
    }

    static String getArea(SalePartner salePartner,String gameId){
        Map<String, String> params = new HashMap<>();
        Map<String, String> header = new HashMap<>();
        header.put("token","KNM9992C401CB36E9B3F2FF79472490CAA34YDJYP");
        params.put("sign", salePartner.getSaleKey());
        params.put("gameId", gameId);
        String result = HttpUtils.doPostForm(OutUrlConstant.CRURLR, params, null);
        return result;
    }

    public static String getRole(String gameId) {
        Map<String, String> params = new HashMap<>();
        params.put("gameId", gameId);
        String result = HttpUtil.doGet("http://api.axyds.com/game/role", params, null);
        System.out.println(result);
        return result;
    }

    public static String getArea(String gameId) {
        Map<String, String> params = new HashMap<>();
        params.put("gameId", gameId);
        String result = HttpUtil.doGet("http://api.axyds.com/game/system", params, null);
        System.out.println(result);
        return result;
    }

    public static String getDZArea(String gameId,String pid) {
        Map<String, String> params = new HashMap<>();
        params.put("gameId", gameId);
//        params.put("pid", pid);
        String result = HttpUtil.doGet("http://api.diguageyouxi.com/game/system", params, null);
        System.out.println(result);
        return result;
    }
}
